<template>
  <van-nav-bar title="修改资料" fixed placeholder left-arrow @click-left="handleBack" />
  <van-form @submit="onSubmit">
    <van-field
      v-model="user.userName"
      label="用户昵称"
      name="userName"
      placeholder="请输入用户昵称"
      :rules="[{ required: true, message: '请输入用户昵称' }]"
    />

    <van-cell title="用户头像" is-link
              :style="{ display: 'flex', alignItems: 'center', height: '80px' }"
              @click="updateAvatar">
      <template #value>
        <van-image
          style="margin-top: 5px"
          v-if="user.avatarUrl"
          width="70"
          height="70"
          :src="user.avatarUrl"
        />
        <input type="file" ref="fileRef" accept="image/*"
               style="display: none;" @change="handleFileUpload">
      </template>
    </van-cell>

    <van-field
      v-model="displayGenderType" 
      name="gender"
      label="用户性别"
      placeholder="请选择类型"
      is-link
      readonly
      @click="showTypePicker = true"
    />

    <van-field
      v-model="user.phone"
      label="手机号"
      name="phone"
      placeholder="请输入手机号"
      :rules="[
        { required: true, message: '请输入手机号' },
        {
          pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
          message: '手机号格式不正确'
        }
      ]"
    />

    <van-field
      v-model="user.email"
      label="邮箱"
      name="email"
      placeholder="请输入邮箱"
      :rules="[
        { required: true, message: '请输入邮箱' },
        {
          pattern:/^[a-zA-Z0-9._%+-]+@qq.com$/,
          message:'请输入@qq.com的邮箱'
        }
      ]"
    />

    <!-- 类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom">
      <van-picker
        :columns="genderOptions"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </van-popup>

    <div class="btn-box">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
      <van-button round block type="default" @click="handleBack">
        返回
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { 
  updateUserInfoService, 
  uploadFileService, 
  getUserInfoService 
} from '@/api/user' // 假设接口文件路径

const router = useRouter()
const fileRef = ref<HTMLInputElement | null>(null)
const showTypePicker = ref(false)
// 存储上传的文件
const magesFiles = ref([]);

// 用户数据 - 使用reactive确保所有属性都是响应式的
const user = ref({
  userName: '',
  avatarUrl: '',
  gender: 0,
  phone: '',
  email: '',
  password: '',
})

// 性别选项
const genderOptions = ref([
  { text: '男', value: 1},
  { text: '女', value: 0 },
])


const displayGenderType = computed({
  get: () => genderOptions.value.find(o => o.value === user.value.gender)?.text || '',
  set: () => {}
})

const onTypeConfirm = ({ selectedOptions }) => {
  user.value.gender = selectedOptions[0]?.value?? ''
  showTypePicker.value = false
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfoService()
    user.value = res.data
  } catch (error) {
    console.error('获取用户信息出错:', error)
    showToast('网络错误，请稍后重试')
  }
}

// 生命周期钩子
onMounted(() => {
  fetchUserInfo()
})

// 处理返回
const handleBack = () => {
  router.back()
}

// 更新头像
const updateAvatar = () => {
  fileRef.value?.click()
}

// 处理文件上传
const handleFileUpload = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files || files.length === 0) {
    showToast('请选择要上传的头像文件')
    return
  }
  
  const file = files[0]
  const formData = new FormData()
  formData.append('file', file)
  
  const response = await uploadFileService(formData);
  console.log('上传成功');
  // 假设response.data是图片URL
  if (typeof response.data ==='string') {
    magesFiles.value = [{ url: response.data }];
  } else {
    magesFiles.value = response.data;
  }
  console.log(magesFiles.value[0].url);
  user.value.avatarUrl = magesFiles.value[0].url;
}

// 表单提交
const onSubmit = async () => {
  try {
    // 复制用户数据，不包含password（如果为空）
    const userData = { ...user.value }
    if (!userData.password) delete userData.password
    
    // 转换性别值以匹配后端要求
    if (userData.gender === 1) userData.gender = 1
    else if (userData.gender === 0) userData.gender = 0
    else userData.gender = null
    
    const res = await updateUserInfoService(userData)
    if (res.code === 0) { 
      showToast('资料更新成功')
      setTimeout(() => {
        router.back()
      }, 1500)
    } else {
      showToast(res.message || '资料更新失败')
    }
  } catch (error) {
    console.error('更新用户信息出错:', error)
    showToast('网络错误，请稍后重试')
  }
}
</script>

<style scoped>
.btn-box {
  margin: 16px;
}

.btn-box button {
  margin-bottom: 10px;
}
</style>